import $http from '@/http';

const State = {
  suser: {}, // 登录用户信息
  user: {
    accountType: null,
    beginTime: '2019-11-01 09:34:47',
    brandCount: 30,
    companyName: null,
    dataMonthNum: 6,
    deadLine: '2019-12-12 09:34:28',
    hasOtherProp: 1,
    hasPriceProp: 1,
    id: 17006,
    lastLogonTime: null,
    name: null,
    passingTime: '2019-09-01 09:35:58',
    phone: null,
    productCount: 20,
    rankingNumber: 50,
    shopCount: 30,
    trendDataMonthNum: 12,
    userId: 2
  }, // 权限用户信息
  pathIds: [1, 2, 3, 4, 5, null], // 权限id
  token: ''
};

// getters
const Getters = {
  token: state => state.token,
  user: state => state.user,
  suser: state => state.suser,
  pathIds: state => state.pathIds
};

// mutations
const Mutations = {
  reset: state => {
    const s = {
      suser: {}, // 登录用户信息
      user: {}, // 权限用户信息
      pathIds: [], // 权限id
      token: ''
    };
    Object.keys(s).forEach(key => {
      state[key] = s[key];
    });
  },
  SET_Token: (state, token) => {
    state.token = token;
  },
  SET_USER: (state, user) => {
    state.user = { ...user };
  },
  SET_PATH: (state, paths) => {
    let ids = paths.map(item => item.pathId);
    state.pathIds = [...ids];
  },
  SET_SUSER: (state, suser) => {
    state.suser = { ...suser };
  }
};
// actions
const Actions = {
  storeUser({ commit }) {
    return new Promise((resolve, reject) => {
      $http
        .post({ map: 'SYSTEM', url: 'getUserAuthConfig' })
        .then(res => {
          const { data } = res;
          if (data['success']) {
            commit('SET_USER', data['data']);
            resolve(data);
          } else {
            reject(data);
          }
        })
        .catch(err => {
          console.error('my error');
          reject(err);
        });
    });
  },
  storeUserPath({ commit }) {
    return new Promise((resolve, reject) => {
      $http
        .post({ map: 'SYSTEM', url: 'getUserPaths' })
        .then(({ data }) => {
          if (data['success']) {
            commit('SET_PATH', data['list']);
            resolve(data);
          } else {
            reject(data);
          }
        })
        .catch(err => {
          reject(err);
        });
    });
  },
  storeSuser({ commit }, suser) {
    commit('SET_SUSER', suser);
  }
};

export default {
  namespaced: true,
  strict: true,
  state: State,
  getters: Getters,
  actions: Actions,
  mutations: Mutations
};
